package licode.unisop.unilite.result;

import lombok.Getter;

import java.io.Serializable;

/**
 * 统一返回结果定义
 *
 * @author licode
 */
@Getter
public class UniResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private int code;
    private String message;
    private boolean success;

    private T data;

    public UniResult() {
        message = "";
        success = true;
    }

    public UniResult(T data) {
        message = "";
        success = true;
        this.data = data;
    }

    protected void setSuccess(boolean success) {
        this.success = success;
    }

    public void setCode(int errCode) {
        this.code = errCode;
        setSuccess(code == 0 || 200 == code);
    }

    public void setMessage(String errMessage) {
        this.message = errMessage;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> UniResult<T> fail(int errCode, String errMessage) {
        UniResult<T> result = new UniResult<T>();

        result.setCode(errCode);
        result.setMessage(errMessage);

        return result;
    }

    public static <T> UniResult<T> of(T data) {
        return UniResult.of(data, 0, "");
    }

    public static <T> UniResult<T> of(T data, int errCode) {
        return UniResult.of(data, errCode);
    }

    public static <T> UniResult<T> of(T data, int errCode, String msg) {
        UniResult<T> result = new UniResult<>(data);

        result.setMessage(msg);
        result.setCode(errCode == 200 ? 0 : errCode);
        result.setData(data);

        return result;
    }
}
